package com.zhp.farmerclient.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhp.farmerclient.common.Result;
import com.zhp.farmerclient.entity.Announce;
import com.zhp.farmerclient.mapper.AnnounceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AnnounceService {

    @Autowired
    public AnnounceMapper announceMapper;

    //分页
    public Result list(Integer page, Integer size){
        Page<Announce> p = new Page<>(page,size);
        QueryWrapper<Announce> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("time");
        IPage<Announce> iPage = announceMapper.selectPage(p,queryWrapper);
        return Result.succ(iPage.getRecords(),iPage.getTotal());
    }
    //部分显示
    public Result part() {
        QueryWrapper<Announce> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("time");
        List<Announce> announces = announceMapper.selectList(queryWrapper);
        return Result.succ(announces,null);
    }

    //详情页
    public Result detail(int id){
        Announce announce = announceMapper.selectById(id);
        return Result.succ(announce,null);
    }
    //新增或修改公告
    public Result publish(Announce announce){

        if(announce.getId()!=null){//修改
            UpdateWrapper<Announce> announceUpdateWrapper = new UpdateWrapper<>();
            announceUpdateWrapper.eq("id",announce.getId());
            announceMapper.update(announce,announceUpdateWrapper);
            return Result.succ();
        }
        else {//新增
            announceMapper.insert(announce);
            return Result.succ();
        }
    }


    //分页显示（查询）
    public Result page(Integer pageNum, Integer pageSize, String title, String content) {
        Page<Announce> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Announce> queryWrapper = new QueryWrapper<>();
        if (!"".equals(title)) {
            queryWrapper.like("title", title);
        }
        if (!"".equals(content)) {
            queryWrapper.like("content", content);
        }
        queryWrapper.orderByDesc("id");
        IPage<Announce> iPage = announceMapper.selectPage(page,queryWrapper);
        return Result.succ(iPage.getRecords(),iPage.getTotal());
    }

    //删除
    public Result delete(Integer id) {
        announceMapper.deleteById(id);
        return Result.succ();
    }

    //批量删除
    public Result deletes(List<Integer> ids) {
        announceMapper.deleteBatchIds(ids);
        return Result.succ();
    }

}
